<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="课程名称" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入课程名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="课程状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="课程状态" clearable style="width: 200px">
            <el-option label="草稿" value="DRAFT" />
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="已下架" value="UNPUBLISHED" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="课程分类" clearable style="width: 200px">
            <el-option label="前端开发" value="1" />
            <el-option label="后端开发" value="2" />
            <el-option label="移动开发" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Plus"
            class="toolbar-button is-primary"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="Edit"
            :disabled="single"
            class="toolbar-button is-success"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="Download"
            class="toolbar-button is-warning"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 课程表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="courseList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="课程封面" align="center" width="100">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 40px"
              :src="scope.row.coverImage || '/default-course.jpg'"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="课程名称" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="课程分类" align="center" prop="categoryName" width="120" />
        <el-table-column label="讲师" align="center" prop="teacherName" width="100" />
        <el-table-column label="价格" align="center" width="100">
          <template #default="scope">
            <span class="price">¥{{ scope.row.price || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学员数" align="center" prop="studentCount" width="80" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              disable-transitions
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="info"
                icon="View"
                @click="handleDetail(scope.row)"
                class="table-operation-button is-info"
                size="small"
              >详情</el-button>
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >修改</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handlePublish" icon="VideoPlay">发布课程</el-dropdown-item>
                    <el-dropdown-item command="handleUnpublish" icon="VideoPause">下架课程</el-dropdown-item>
                    <el-dropdown-item command="handleChapters" icon="Document">章节管理</el-dropdown-item>
                    <el-dropdown-item command="handleStatistics" icon="DataAnalysis">数据统计</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改课程配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="courseFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择课程分类">
                <el-option label="前端开发" value="1" />
                <el-option label="后端开发" value="2" />
                <el-option label="移动开发" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程价格" prop="price">
              <el-input-number v-model="form.price" :min="0" :precision="2" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择课程难度">
                <el-option label="入门" value="BEGINNER" />
                <el-option label="进阶" value="INTERMEDIATE" />
                <el-option label="高级" value="ADVANCED" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程简介" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入课程简介" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程详情" prop="content">
              <el-input v-model="form.content" type="textarea" placeholder="请输入课程详情" :rows="6" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入课程标签，多个标签用逗号分隔" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCourseList, createCourse, updateCourse, deleteCourse, publishCourse, unpublishCourse } from '@/api/classroom'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const courseList = ref([])
const title = ref('')
const open = ref(false)
const queryFormRef = ref()
const courseFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  status: undefined,
  categoryId: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  title: undefined,
  description: undefined,
  content: undefined,
  categoryId: undefined,
  price: 0,
  difficulty: 'BEGINNER',
  tags: undefined
})

// 表单校验规则
const rules = reactive({
  title: [{ required: true, message: '课程名称不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '课程分类不能为空', trigger: 'change' }],
  description: [{ required: true, message: '课程简介不能为空', trigger: 'blur' }]
})

// 获取课程列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getCourseList(queryParams)
    courseList.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('获取课程列表失败:', error)
    // 模拟数据
    courseList.value = [
      {
        id: 1,
        title: 'Vue 3 从入门到精通',
        categoryName: '前端开发',
        teacherName: '张老师',
        price: 199.00,
        studentCount: 1234,
        status: 'PUBLISHED',
        createTime: new Date()
      },
      {
        id: 2,
        title: 'Spring Boot 微服务开发',
        categoryName: '后端开发',
        teacherName: '李老师',
        price: 299.00,
        studentCount: 856,
        status: 'DRAFT',
        createTime: new Date()
      }
    ]
    total.value = 2
  } finally {
    loading.value = false
  }
}

// 状态类型
const getStatusType = (status) => {
  const statusMap = {
    'DRAFT': 'info',
    'PUBLISHED': 'success',
    'UNPUBLISHED': 'warning'
  }
  return statusMap[status] || 'info'
}

// 状态文本
const getStatusText = (status) => {
  const statusMap = {
    'DRAFT': '草稿',
    'PUBLISHED': '已发布',
    'UNPUBLISHED': '已下架'
  }
  return statusMap[status] || '未知'
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加课程'
}

// 查看详情操作
const handleDetail = (row) => {
  router.push(`/classroom/course/detail/${row.id}`)
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const courseId = row.id || ids.value[0]
  Object.assign(form, row)
  open.value = true
  title.value = '修改课程'
}

// 删除按钮操作
const handleDelete = (row) => {
  const courseIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除课程编号为"' + courseIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteCourse(courseIds[0])
    getList()
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handlePublish':
      handlePublish(row)
      break
    case 'handleUnpublish':
      handleUnpublish(row)
      break
    case 'handleChapters':
      handleChapters(row)
      break
    case 'handleStatistics':
      handleStatistics(row)
      break
    default:
      break
  }
}

// 发布课程
const handlePublish = async (row) => {
  try {
    await publishCourse(row.id)
    ElMessage.success('发布成功')
    getList()
  } catch (error) {
    console.error('发布失败:', error)
  }
}

// 下架课程
const handleUnpublish = async (row) => {
  try {
    await unpublishCourse(row.id)
    ElMessage.success('下架成功')
    getList()
  } catch (error) {
    console.error('下架失败:', error)
  }
}

// 章节管理
const handleChapters = (row) => {
  ElMessage.info('章节管理功能开发中...')
}

// 数据统计
const handleStatistics = (row) => {
  ElMessage.info('数据统计功能开发中...')
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    title: undefined,
    description: undefined,
    content: undefined,
    categoryId: undefined,
    price: 0,
    difficulty: 'BEGINNER',
    tags: undefined
  })
  courseFormRef.value?.resetFields()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 提交表单
const submitForm = () => {
  courseFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await updateCourse(form.id, form)
          ElMessage.success('修改成功')
        } else {
          await createCourse(form)
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}
</style>
